﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Microsoft.Win32;

namespace TapTapServer
{


    public class MyServer : CsHTTPServer
    {
        public string Folder;

        public MyServer()
            : base()
        {
            this.Folder = "c:\\www";
        }

        public MyServer(int thePort, string theFolder)
            : base(thePort)
        {
            this.Folder = theFolder;
        }

        public override void OnResponse(ref HTTPRequestStruct rq, ref HTTPResponseStruct rp)
        {
            WriteLog("File requested: " + rq.URL);
            if (rq.URL.StartsWith("http://"))
            {
                rq.URL = rq.URL.Substring(7);
                rq.URL = rq.URL.Substring(rq.URL.IndexOf("/"));
            }

            string path = this.Folder + "\\" + rq.URL.Replace("/", "\\");

            if (rq.URL == "/tapplications/ttr/v3.0/index.php") //needs to be generated
            {
                string data = "";
                if (rq.Method == "POST")
                {
                    string body = ASCIIEncoding.ASCII.GetString(rq.BodyData);
                    if (body.Contains("song_ids"))
                    {
                        body = body.Substring(body.IndexOf("song_ids") + 9);
                        body = body.Substring(0, body.IndexOf("Content-Disposition"));
                        body = body.Trim();
                        body = body.Substring(0, body.IndexOf("\r\n"));

                        data = File.ReadAllText(Path.Combine(Settings.Instance.ServerRootPath, @"tapplications\ttr\v3.0\", body + "Tracks.plist"));
                    }
                }
                else
                {
                    data = File.ReadAllText(Path.Combine(Settings.Instance.ServerRootPath, @"tapplications\ttr\v3.0\extremeTracks.plist"));
                }


                rp.BodyData = Encoding.ASCII.GetBytes(data);

            }


            if (Directory.Exists(path))
            {
                if (File.Exists(Path.Combine(path, "default.htm")))
                    path += "\\default.htm";
                else
                {
                    string[] dirs = Directory.GetDirectories(path);
                    string[] files = Directory.GetFiles(path);

                    string bodyStr = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n";
                    bodyStr += "<HTML><HEAD>\n";
                    bodyStr += "<META http-equiv=Content-Type content=\"text/html; charset=windows-1252\">\n";
                    bodyStr += "</HEAD>\n";
                    bodyStr += "<BODY><p>Folder listing, to do not see this add a 'default.htm' document\n<p>\n";
                    for (int i = 0; i < dirs.Length; i++)
                        bodyStr += "<br><a href = \"" + rq.URL + Path.GetFileName(dirs[i]) + "/\">[" + Path.GetFileName(dirs[i]) + "]</a>\n";
                    for (int i = 0; i < files.Length; i++)
                        bodyStr += "<br><a href = \"" + rq.URL + Path.GetFileName(files[i]) + "\">" + Path.GetFileName(files[i]) + "</a>\n";
                    bodyStr += "</BODY></HTML>\n";

                    rp.BodyData = Encoding.ASCII.GetBytes(bodyStr);
                    return;
                }
            }

            if (File.Exists(path))
            {
                try
                {
                    RegistryKey rk = Registry.ClassesRoot.OpenSubKey(Path.GetExtension(path), true);
                    // Get the data from a specified item in the key.

                    String s = "";
                    if (rk != null) { s = (String)rk.GetValue("Content Type"); }


                    // Open the stream and read it back.
                    rp.fs = File.Open(path, FileMode.Open);
                    if (s != "" && s != null)
                        rp.Headers["Content-type"] = s;
                }
                catch (Exception) { }
            }
            else
            {

                rp.status = (int)RespState.NOT_FOUND;

                string bodyStr = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n";
                bodyStr += "<HTML><HEAD>\n";
                bodyStr += "<META http-equiv=Content-Type content=\"text/html; charset=windows-1252\">\n";
                bodyStr += "</HEAD>\n";
                bodyStr += "<BODY>File not found!!</BODY></HTML>\n";

                rp.BodyData = Encoding.ASCII.GetBytes(bodyStr);
                WriteLog("--File not found: " + path);
            }

        }
    }
}
